import router from "@/router";
import store from "@/store";
import {getToken} from "@/utils/auth";
import {Message} from "element-ui";

const whiteList = [
    '/admin/login',
    '/frontEnd/userLogin',
    '/frontEnd/homePage',
    '/frontEnd/articleDetail',
    '/frontEnd/userReg',
    '/frontEnd/user/homePage',
    '/frontEnd/PersonalCommentsList',
    '/frontEnd/space',
    '/frontEnd/userdata',
    '/frontEnd/postArticle',
]

router.beforeEach((to, from, next) => {
    if (getToken()) {
        if (to.path === '/admin/login') {
            console.log('to',to);
            next({path: '/admin'})
        } else {
            if (store.getters.roles.length === 0) {
                // 判断当前用户是否已拉取完user_info信息
                store.dispatch('GetInfo').then(response => {
                    store.dispatch('GenerateRoutes').then(accessRoutes => {
                        // 根据roles权限生成可访问的路由表
                        router.addRoutes(accessRoutes);
                        next({ ...to, replace: true })
                    })
                }).catch(err => {
                    Message.error(err)
                })
            } else {
                next()
            }
        }
    } else {
        // 没有token
        if (whiteList.indexOf(to.path) !== -1) {
            // 在免登录白名单，直接进入
            next()
        } else {
            if (to.path.includes('/admin')) {
                next(`/admin/login?redirect=${to.fullPath}`)
            } else {
                next(`/frontEnd/userLogin?redirect=${to.fullPath}`)
            }
        }
    }
})
